package com.alfred.redis.config;

import com.alfred.redis.limit.RedisLimit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

/**
 * Function: 限流 bean
 *
 * @author Alfred
 * Date: 23/04/2018 23:45
 * @since JDK 1.8
 */
@Configuration
@Slf4j
public class RedisLimitConfig {


    @Value("${redis.limit}")
    private int limit;
    /**
     * 单机还是集群：1表示单机、2表示集群
     */
    @Value("${redis.single.or.cluster}")
    private int singleOrCluster;


    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    /**
     * 初始化限流Bean
     * @return
     */
    @Bean
    public RedisLimit build() {
        RedisLimit redisLimit = new RedisLimit.Builder(jedisConnectionFactory, singleOrCluster)
                .limit(limit)
                .build();
        return redisLimit;
    }


    /**
     * 读取限流脚本
     *
     * @return
     */
    @Bean
    public DefaultRedisScript<Number> redisluaScript() {
        DefaultRedisScript<Number> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("limit.lua")));
        redisScript.setResultType(Number.class);
        return redisScript;
    }

}
